#!/usr/bin/env python
#-*-coding:utf-8-*-


from flask import Flask
from flask import render_template , request, Request,jsonify
from flask import abort
import json

import seg_service
import tag_service
import ner_service
import pre_process

import seg_crf_services
import ner_pos_services



app = Flask(__name__)


def gen_seg_html(words, tags):
    html_format = "<dd class='%s'>%s</dd>"
    html_list = [html_format%(tag, "/".join([w, tag])) for w, tag in zip(words,tags)]
    html = "".join(html_list)
    return html


def gen_ner_html(ner_labels):
    html = ""
    for item in ner_labels:
        label = item[2]
        word = item[3]
        if label !="O":
            word = "/".join([item[3], label])
        html += "<dd class='%s'>%s</dd>"%(label, word)
    return html

@app.route("/", methods=["GET"] )
def hello():
    return render_template("demo.html")


@app.route("/nlp/lexical", methods=["POST"])
def reset_api():
    param = request.json
    text = param.get("text")
    if not text:
        abort(400, "text is null")
    is_tag = param.get("tag", 0)
    is_ner = param.get("ner", 0)
    dict_name = param.get("dict", "")
    # seg_results, words = seg_crf_services.recognise(text)

    seg_results, words = seg_service.seg_by_local_model(text)
    tags = []
    if is_tag :
        tags = tag_service.tag_by_local_model(words)

    ners = []
    if is_ner:
        ner_words = [item[0] for item in seg_results]
        segs = [item[1] for item in seg_results]

        ner_pos = []
        for w, p in zip(words, tags):
            ner_pos += [p]*len(w)
        ners = ner_pos_services.ner_by_local_model(ner_words, segs, ner_pos)

    ners = [item for item in ners if item[2] != "O"]
    result = {"words":words, "tags":tags, "ners": ners}

    return jsonify(result)



@app.route("/nlp", methods=["POST"])
def demo():
    text = request.form["text"]
    text = pre_process.pre_handle_text(text)
    seg_results, words = seg_service.seg_by_local_model(text)


    # seg_results , words = seg_crf_services.recognise(text)
    # local_seg_words = [w for w in local_seg_words if w.strip()]

    tags = tag_service.tag_by_local_model(words)

    ner_words = [item[0] for item in seg_results]
    segs = [item[1] for item in seg_results]
    ner_pos = []
    for w, p in zip(words, tags):
        ner_pos += [p]*len(w)
    # ners = ner_service.ner_by_local_model(ner_words, segs)
    ners = ner_pos_services.ner_by_local_model(ner_words, segs, ner_pos)

    ner_html = gen_ner_html(ners)
    result = {"seg_result": gen_seg_html(words, tags), "ner_result":ner_html}
    # return json.dumps(result)
    return jsonify(result)



if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0", port=5556)